package com.sen.app.schedul.jobs;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.StatefulJob;
import org.springframework.scheduling.quartz.QuartzJobBean;

import com.sen.app.schedul.core.utils.DirUtils;
import com.sen.app.schedul.entity.JobConfigEntity;
import com.sen.app.schedul.services.SchedulManagerService;

/**
 * 调度管理job类
 * 
 * @author sen
 */
public class SchedulMangerJob extends QuartzJobBean implements StatefulJob {
    
    /** 日志记录器 */
    private static Logger logger = Logger.getLogger(SchedulMangerJob.class);
	
    /**
     * 调度管理service，通过spring注入
     */
	private SchedulManagerService schedulMangerService;
	
	/**
     * 缓存所有job配置信息,map中的key为文件名
     */
    private static Map<String, JobConfigEntity> cache;

	@Override
	protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
		System.out.println("SchedulMangerJob execute...");
		initCache();
		
		Scheduler scheduler = context.getScheduler();
		
		/*
        JobDetail jobDetail = new JobDetail();
        jobDetail.setName("job_1");
        jobDetail.setJobClass(QueryJob.class);
        try {
			scheduler.addJob(jobDetail, true);
		} catch (SchedulerException e) {
			e.printStackTrace();
		}
		
		CronTrigger cronTrigger = new CronTrigger("cron_1", Scheduler.DEFAULT_GROUP, jobDetail.getName(), Scheduler.DEFAULT_GROUP);
		try {
			cronTrigger.setCronExpression("0/10 * * * * ?");
		} catch (ParseException e) {
			e.printStackTrace();
		}
		
		try {
			scheduler.scheduleJob(cronTrigger);
		} catch (SchedulerException e) {
			e.printStackTrace();
		}*/
		
		try {
			System.out.println(scheduler.getSchedulerName() + " success!");
		} catch (SchedulerException e) {
			e.printStackTrace();
		}
		
	}

	private void initCache() {
	    if (null == cache) {
	        cache = schedulMangerService.getAllJobConfig();
            if (logger.isDebugEnabled()) 
                logger.debug("本次缓存job总个数".concat(cache.size()+"."));
	    }
	}

    public SchedulManagerService getSchedulMangerService() {
        return schedulMangerService;
    }

    public void setSchedulMangerService(SchedulManagerService schedulMangerService) {
        this.schedulMangerService = schedulMangerService;
    }

}
